#!/bin/sh
# 获取tomcat进程ID  /usr/local/tomcat_ds_api
TomcatID=$(ps -ef |grep tomcat |grep -w $tomcat_name|grep -v 'grep'|awk '{print $2}')  
# tomcat启动程序
StartTomcat=$tomcat_home/bin/startup.sh
# 日志输出 
if [ -f $tomcatMonitorLog ]; then
   echo "日志文件已创建"
else
   echo "日志文件为创建,马上创建!"
	touch $tomcatMonitorLog
fi
#tomcatMonitorLog=/tmp/yanglao/tomcatMonitor.log 
TryConnection(){
	echo $tomcat_name 
	echo '$tomcat_name'
  TryTomcatID=$(ps -ef |grep tomcat |grep -w $tomcat_name|grep -v 'grep'|awk '{print $2}')  
  echo "[info]开始重新查看tomcat进程:$TryTomcatID...[$(date +'%F %H:%M:%S')]"  
  if [[ $TryTomcatID ]];then
    echo "[info]当前tomcat进程ID为:$TryTomcatID,继续重新检测接口..."  
    # 检测是否启动成功(成功的话接口会返回状态"200")  
    TomcatServiceCodeTry=$(curl -s -m 10 --connect-timeout 10 $webUrl -w %{http_code}) 
    if [[ $TomcatServiceCodeTry -eq 200 ]];then  
        echo "[info]系统接口返回码为$TomcatServiceCodeTry,tomcat重启成功,访问系统接口正常......"  
        echo "[error]发送告警关闭邮件"  
        echo "tomcat重启成功，访问系统接口正常 [$(date +'%F %H:%M:%S')]"|mail -s "智能养老项目告警关闭" $email_address
    else
    sleep 30
    TryConnection
    fi  
  else 
    sleep 30
    TryConnection
  fi
}

Monitor() 
{  
  echo "[info]开始监控tomcat...[$(date +'%F %H:%M:%S')]"  
  if [[ $TomcatID ]];then # 这里判断TOMCAT进程是否存在  
    echo "[info]当前tomcat进程ID为:$TomcatID,继续检测系统接口..."  
    # 检测是否启动成功(成功的话接口会返回状态"200")  
    TomcatServiceCode=$(curl -s -m 10 --connect-timeout 10 $webUrl -w %{http_code}) 
    if [[ $TomcatServiceCode -eq 200 ]];then
        echo "[info]接口返回码为$TomcatServiceCode,tomcat运行正常,访问系统接口正常......"  
    else  
        echo "[error]访问系统接口出错,请注意......状态码为$TomcatServiceCode"  
        echo "[error]访问系统接口出错,开始重启tomcat"  
		echo "[error]发送告警开启邮件"  
		echo "由于访问系统接口出错，tomcat开始自动重启 [$(date +'%F %H:%M:%S')]"|mail -s "智能养老项目告警开启" $email_address
        kill -9 $TomcatID  # 杀掉原tomcat进程  
        sleep 3  
        rm -rf $TomcatCache # 清理tomcat缓存  
        $StartTomcat  
        sleep 3m
        TryConnection #检查是否启动成功
    fi  
  else  
    echo "[error]tomcat进程不存在!tomcat开始自动重启..."  
    echo "[info]$StartTomcat,请稍候......"  
	echo "[error]发送告警开启邮件"  
	echo "由于tomcat进程不存在   tomcat开始自动重启 [$(date +'%F %H:%M:%S')]"|mail -s "智能养老项目告警开启" $email_address
    rm -rf $TomcatCache  
    $StartTomcat  
    sleep 3m
    TryConnection #检查是否启动成功
  fi  
  echo "------------------------------"  
}  
Monitor>>$tomcatMonitorLog
